package com.bawei.park2211a.park

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.bawei.base.bean.NoticeEntity
import com.bawei.base.net.ApiService
import java.io.IOException

class ParkDataSource(var apiService: ApiService) : PagingSource<Int, NoticeEntity>() {
    override fun getRefreshKey(state: PagingState<Int, NoticeEntity>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, NoticeEntity> {
        try {
            // 解析并验证 params.key，确保其为合法整数，默认值为 0
            val page = params.key ?: 0
            // 调用 API 并校验返回结果
            val noticeResponse = apiService.notice(page, 5)
            val nextPage =
                if (noticeResponse.data.isNotEmpty()) page + 1 else null
            // 返回分页结果
            return LoadResult.Page(noticeResponse.data, null, nextPage)
        } catch (e: IOException) {
            // 特定处理网络相关异常
            return LoadResult.Error(e)
        }
    }
}